package edu.qichen.onlineBlog.framework.validata;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import edu.qichen.onlineBlog.framework.exception.BusinessException;
import edu.qichen.onlineBlog.framework.validata.annptation.AtLeastOneNotNull;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import org.springframework.context.i18n.LocaleContextHolder;

import java.lang.annotation.Annotation;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;

/**
 * 参数校验工具类
 **/
public class ValidatorUtil {
    /**
     * 校验对象，抛出异常
     *
     * @param object 对象（集合不可用）
     * @param groups 校验规则组
     */
    public static void validateEntity(Object object, Class<?>... groups) {
        Locale.setDefault(LocaleContextHolder.getLocale());
        Set<ConstraintViolation<Object>> constraintViolations =
                Objects.requireNonNull(SpringUtil.getBean(Validator.class)).validate(object, groups);
        if (CollectionUtil.isNotEmpty(constraintViolations)) {
            ConstraintViolation<Object> next = constraintViolations.iterator().next();

            String errorMsg = Optional.ofNullable(next.getPropertyPath().toString())
                    .orElse(StrUtil.EMPTY);
            if (StrUtil.isNotBlank(errorMsg)) {
                errorMsg = errorMsg.concat(":");
            }

            Annotation annotation = next.getConstraintDescriptor().getAnnotation();
            if (annotation instanceof AtLeastOneNotNull atLeastOneNotNull) {
                errorMsg = errorMsg.concat(ArrayUtil.toString(atLeastOneNotNull.value()) + " ");
            }

            errorMsg = errorMsg.concat(next.getMessage());

            throw BusinessException.build(errorMsg);
        }
    }

    /**
     * 校验对象，返回异常
     *
     * @param object 对象（集合不可用）
     * @param groups 校验规则组
     */
    public static String validateEntityReturnErrorMsg(Object object, Class<?>... groups) {
        Validator validator = SpringUtil.getBean(Validator.class);
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (CollectionUtil.isEmpty(constraintViolations)) {
            return null;
        }

        return constraintViolations.iterator().next().getMessage();
    }
}
